package threadDemo;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/***
 * 信号量的使用
 * semaphore 用来确定线程池中running状态的线程数量
 *
 * semaphone 数量 < running状态的线程数量时，线程池中无法启动新的waiting线程
 * 当一个running线程执行完毕后，semaphore
 */
public class SemaphoreDemo {
    public static void main(String[] args) {

        ExecutorService excutor = Executors.newCachedThreadPool();
        //这里的信号量大于等待执行线程个数时，线程就会并发执行而不是同步
        //因为线程release后，剩余的信号量还是大于0，其余的线程在调用acquire方法时不会被阻塞
        final Semaphore semaphore = new Semaphore(3, true);
        for (int i = 0; i < 10; i++) {
/*            excutor.execute(()->{
                try {
                    semaphore.acquire();//获取信号灯许可

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread " + Thread.currentThread().getName() + " 进入" + "当前系统的并发数是：" + (3 - semaphore.availablePermits()));
                try {
                    Thread.sleep(new Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread " + Thread.currentThread().getName() + " 即将离开");
                semaphore.release();//释放信号灯
                System.out.println("Thread " + Thread.currentThread().getName() + " 已经离开，当前系统的并发数是：" + (3 - semaphore.availablePermits()));
            });*/

            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();//获取信号灯许可

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread " + Thread.currentThread().getName() + " 进入" + "当前系统的并发数是：" + (3 - semaphore.availablePermits()));
                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread " + Thread.currentThread().getName() + " 即将离开");
                    semaphore.release();//释放信号灯
                    System.out.println("Thread " + Thread.currentThread().getName() + " 已经离开，当前系统的并发数是：" + (3 - semaphore.availablePermits()));
                }
            };
            excutor.execute(runnable);
        }

    }
}
